package codegenerator.generator;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;

import baytony.util.log.Log;
import codegenerator.CodeGeneratorException;
import codegenerator.CommonHelper;
import codegenerator.CssFileBean;
import codegenerator.FileBean;
import codegenerator.GeneratorHelper;
import codegenerator.TableInfo;
import codegenerator.config.GeneratorConfigration;

public class CssGenerator implements IGenerator {
	
	private final Logger logger = Log.getLogger();
	protected GeneratorHelper generatorHelper;
	private static final String CSS_CONTENT = "#tableName {}";
	
	
	public void setGeneratorHelper(GeneratorHelper generatorHelper) {
		this.generatorHelper = generatorHelper;
	}

	@Override
	public void generate(TableInfo... tables) throws CodeGeneratorException {
		String content = this.createContent(tables);
		FileBean fb = new CssFileBean();		
		fb.setFileName("common");
		fb.setContent(content);
		fb.setPath(generatorHelper.getCssOutputPath());
		this.touchFile(fb);
	}
	
	private String createContent(TableInfo... tables) {
		StringBuffer sb = new StringBuffer();
		String content = "";
		for(TableInfo table : tables) {
			content = CSS_CONTENT;
			content = content.replaceAll("tableName", CommonHelper.table2ClassName(table.getName()));
			sb.append(content);
			sb.append(GeneratorConfigration.SEPARATOR);
			sb.append(GeneratorConfigration.SEPARATOR);
		}
		return sb.toString();
	}

	@Override
	public void touchFile(FileBean fb) {
		File file = new File(generatorHelper.getOutputPath() + fb.getPath() + fb.getFileName() + fb.getExtName());
		try {
			FileUtils.writeStringToFile(file, fb.getContent(), generatorHelper.getFileEncode());
		} catch (IOException e) {
			logger.error("create file fail, fileName : " + fb.getFileName());
			Log.logStackTrace(e);
		}
	} 

}
